package wymiana.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import wymiana.domain.Authorities;
import wymiana.domain.User;

@Repository
public class UserDao extends GenericDao<User> {

	@Autowired
	public UserDao(SessionFactory sf) {
		super(User.class, sf);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAll() {
		return getHibernateTemplate().find(
				"from User user order by user.username");
	}

	@SuppressWarnings("unchecked")
	public List<User> getUserSearch(String term, int LIMIT) {
		List<User> list = this.getSession().createCriteria(User.class)
				.add(Restrictions.like("username", term, MatchMode.ANYWHERE))
				.createCriteria("authorities")
				.add(Restrictions.eq("authority", "ROLE_USER"))
				.setMaxResults(LIMIT).list();
		return list;
	}

	public User addAdminRole(final User user) {
		Authorities a = new Authorities(user, "ROLE_ADMIN");
		user.getAuthorities().add(a);
		saveOrUpdate(user);
		return user;
		
		
	}
}
